<template>
    <el-card>
        <div class="search-bar">
            <el-input placeholder="查询关键字-不输入查询所有" class="input-with-select"
                clearable
                v-model="query"
            >
                <template #append>
                    <el-button type="success" icon="el-icon-search"
                        @click="findUsersByKey()"
                    ></el-button>
                </template>
            </el-input>
            <el-button type="primary" @click="openNewUserModel()">添加用户</el-button>
        </div>
        <el-table border :data="users">
            <el-table-column label="序号" type="index" width="60px"></el-table-column>
            <el-table-column label="登录名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <!-- el-table-column 中一但启用了组件分发功能，prop属性将失去作用 -->
            <el-table-column label="状态">
                <template #default="{ row }">
                    <!-- {{ row }} -->
                    <el-switch v-model="row.mg_state" @change="changeUserState(row,$event)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180px">
                <template #default="{ row }">
                    <el-button type="primary" size="mini" icon="el-icon-edit" @click="openUpdateUserModel(row)"></el-button>
                    <el-popconfirm class="delete-btn" title="确定删除当前用户吗?"
                        @confirm="removeUser(row.id)"
                    >
                        <template #reference>
                            <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
                        </template>
                    </el-popconfirm>
                    <el-button type="warning" size="mini" icon="el-icon-setting" @click="openUserRoleModel(row)"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10, 15, 20, 25, 30]"
            :current-page="params.pagenum"
            :page-size="params.pagesize"
            :total="total"
            @current-change="changePage"
            @size-change="changeSize"
        >
        </el-pagination>
        <!-- 用户权限修改 -->
        <el-dialog title="用户权限修改" :visible.sync="userRoleFlag" >
            <el-form label-width="100px">
                <el-form-item label="当前用户">
                    <el-input :value="userRole.username" readonly></el-input>
                </el-form-item>
                <el-form-item label="当前角色">
                    <el-input :value="userRole.role_name" readonly></el-input>
                </el-form-item>
                <el-form-item label="新角色分配">
                    <el-select v-model="userRole.rid" placeholder="请选择">                
                        <el-option v-for="r in roles" :key="r.id" :value="r.id" :label="r.roleName"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="userRoleFlag = false">取 消</el-button>
                <el-button type="primary" @click="changeUserRole()">确 定</el-button>
            </template>
        </el-dialog>
        <!-- 用户添加 -->
        <el-dialog title="添加新用户" :visible.sync="newUserFlag">
            <el-form label-width="100px" :model="newUser" :rules="$rules.user" ref="newUserForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="newUser.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input  v-model="newUser.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="newUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="newUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="newUserFlag = false">取 消</el-button>
                <el-button type="primary" @click="insertNewUser()">确 定</el-button>
            </template>
        </el-dialog>
        <!-- 用户修改 -->
        <el-dialog title="用户信息更新" :visible.sync="updateUserFlag">
            <el-form label-width="100px" :model="updateUser" :rules="$rules.user" ref="updateUserForm">
                <el-form-item label="用户名">
                    <el-input :value="updateUser.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="updateUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="updateUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="updateUserFlag = false">取 消</el-button>
                <el-button type="primary" @click="updateUserInfo()">确 定</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script>
export default {
    data() {
        return {
            // -------------------
            roles:[],
            userRoleFlag:false,
            userRole:{},
            // -------------------
            newUserFlag:false,
            newUser:{
                username:"",
                password:"",
                email:"",
                mobile:""
            },
            // -------------------
            updateUserFlag:false,
            updateUser:{
                username:"",
                email:"",
                mobile:""
            },
            // -------------------
            users:[],
            query:"",
            params:{
                query:"",
                pagenum:1,
                pagesize:5
            },
            total:0
        }
    },
    methods:{
        changeSize(pagesize){
            // console.log(pagesize);
            this.params.pagesize = pagesize;
            this.params.pagenum = 1;
            this.findUserList();
        },
        changePage(pagenum){
            // console.log("页码改变:",pagenum);
            this.params.pagenum = pagenum;
            this.findUserList();
        },
        findUsersByKey(){
            this.params.query = this.query;
            this.params.pagenum = 1;
            this.findUserList();
        },
        openUserRoleModel(row){
            this.userRole = row;
            this.userRoleFlag = true;
        },
        openUpdateUserModel(row){
            this.updateUserFlag = true;
            this.$nextTick(()=>{
                this.$refs.updateUserForm.resetFields();
                this.updateUser = { ...row };
            })
        },
        openNewUserModel(){
            this.newUserFlag = true;
            this.$nextTick(()=>{
                this.$refs.newUserForm.resetFields();
            })
        },
        async insertNewUser(){
            try {
                await this.$refs.newUserForm.validate();
                let res = await this.$api.addNewUser(this.newUser);
                if(res){
                    this.newUserFlag = false;
                    this.params.query = "";
                    this.params.pagenum = 1;
                    this.findUserList();
                }
            } catch (error) {
                // 数据校验错误
                // console.log("数据校验不通过",error);
            }
        },
        async updateUserInfo(){
            try {
                await this.$refs.updateUserForm.validate();
                let res = await this.$api.updateUser(this.updateUser.id,{
                    email:this.updateUser.email,
                    mobile:this.updateUser.mobile
                });
                if(res){
                    this.$message.success("用户更新成功");
                    this.updateUserFlag = false;
                    this.findUserList();
                }
            } catch (error) {
                // 数据校验错误
                // console.log("数据校验不通过",error);
            }
        },
        async findUserList(){
            this.query = this.params.query;
            let { total,users } = await this.$api.loadUsers(this.params);
            // console.log(total,users);
            this.total = total;
            this.users = users;
        },
        async changeUserState(user,state){
            // console.log(user,state);
            let newUser = await this.$api.modfilyUserState(user.id,state);
            if(!newUser){
                user.mg_state = !state;
            }
            // console.log(newUser);
        },
        async removeUser(uid){
            let flag = await this.$api.deleteUserById(uid);
            if(flag){
                this.$message.success( "删除成功" );
                let countPage = Math.ceil( this.total / this.params.pagesize );
                let endPageSize = this.total % this.params.pagesize;
                if(countPage==this.params.pagenum&endPageSize==1){
                    this.params.pagenum -= 1;
                }
                this.findUserList();
            }
        },
        async changeUserRole(){
            let data = await this.$api.changeUserRole(this.userRole.id,this.userRole.rid);
            // console.log(data);
            if(data){
                this.userRoleFlag = false;
                this.findUserList();
            }
        },
        // ---------
        async loadRoleList(){
            this.roles = await this.$api.loadRoles();
        }
    },
    created(){
        this.findUserList();
        this.loadRoleList();
    }
};
</script>

<style lang="less" scoped>
.search-bar {
    margin-bottom: 20px;
    .el-input {
        width: 500px;
        margin-right: 30px;
    }
}
.el-pagination{
    margin-top: 20px;
}
.delete-btn{
    margin: 0px 6px;
}
.el-select{
    width: 100%;
}
.el-form-item::v-deep .el-form-item__label{
    text-align: justify;
    text-align-last: justify;
    position: relative;
    padding-left: 12px;
    &::before{
        position: absolute;
        left: 0px;
    }
}
</style>